package cn.xo68.ide.plugin.common.component;

import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ProjectManagerListener;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.messages.MessageBusConnection;
import org.apache.log4j.spi.LoggingEvent;

import java.util.LinkedList;
import java.util.List;

/**
 * 日志输出 应用组件
 * @author wuxie
 */
public class ToolSuiteLogOutput implements ApplicationComponent, Disposable {



    private final List<ToolSuiteConsole> consoles;


    public ToolSuiteLogOutput() {
        consoles = new LinkedList<>();
    }

    @Override
    public void initComponent() {
        MessageBusConnection busConnection = ApplicationManager.getApplication().getMessageBus().connect(this);
        busConnection.subscribe(ProjectManager.TOPIC, new ProjectListener());
    }

    public void  log(LoggingEvent event, String msg){
        //super.append(event);
        switch (event.getLevel().toInt()){
            case 40000:
                for (ToolSuiteConsole c : consoles) {
                    c.error(msg, event.getThrowableInformation().getThrowable());
                }
                break;
            default:
                for (ToolSuiteConsole c : consoles) {
                    c.info(msg);
                }
        }
        //ApplicationManager.getApplication().get
    }

    void addConsole(ToolSuiteConsole console) {
        this.consoles.add(console);
    }

    void removeConsole(ToolSuiteConsole console) {
        this.consoles.remove(console);
    }

    @Override
    public void dispose() {
        Disposer.dispose(this);
    }

    private class ProjectListener implements ProjectManagerListener {

        @Override public void projectOpened(Project project) {
            ToolSuiteConsole toolSuiteConsole=project.getComponent(ToolSuiteConsole.class);
            if(toolSuiteConsole!=null){
                addConsole(toolSuiteConsole);
            }

        }

        @Override public void projectClosed(Project project) {
            //nothing to do
            ToolSuiteConsole toolSuiteConsole=project.getComponent(ToolSuiteConsole.class);
            if(toolSuiteConsole!=null){
                removeConsole(toolSuiteConsole);
            }
        }

        @Override public void projectClosing(Project project) {
            // removeConsole(project.getComponent(ToolSuiteConsole.class));
        }
    }
}
